//
//  viewCategory.m
//  cloud
//
//  Created by jack ray on 11-4-16.
//  Copyright 2011年 oulin. All rights reserved.
//

#import "UIView+expanded.h"
#import <QuartzCore/QuartzCore.h>
#import "SDDataCache.h"
#import "NSString+expanded.h"
//#import "UIImage+expanded.h"

#define showProgressIndicator_width 250

@implementation UIView(Addition)

- (void) autoResize:(UIViewAutoresizing) mask
{
    self.autoresizingMask = mask;
    self.autoresizesSubviews = YES;
}

-(BOOL) containsSubView:(UIView *)subView
{
    for (UIView *view in [self subviews]) {
        if ([view isEqual:subView]) {
            return YES;
        }
    }
    return NO;
}
//-(BOOL) isKindOfClass: classObj 判断是否是这个类，包括这个类的子类和父类的实例；
//-(BOOL) isMemberOfClass: classObj 判断是否是这个类的实例,不包括子类或者父类；
-(BOOL) containsSubViewOfClassType:(Class)class {
    for (UIView *view in [self subviews]) {
        if ([view isMemberOfClass:class]) {
            return YES;
        }
    }
    return NO;
}

- (CGPoint)frameOrigin {
    return self.frame.origin;
}

- (void)setFrameOrigin:(CGPoint)newOrigin {
    self.frame = CGRectMake(newOrigin.x, newOrigin.y, self.frame.size.width, self.frame.size.height);
}

- (CGSize)frameSize {
    return self.frame.size;
}

- (void)setFrameSize:(CGSize)newSize {
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y,
                            newSize.width, newSize.height);
}

- (CGFloat)frameX {
    return self.frame.origin.x;
}

- (void)setFrameX:(CGFloat)newX {
    self.frame = CGRectMake(newX, self.frame.origin.y,
                            self.frame.size.width, self.frame.size.height);
}

- (CGFloat)frameY {
    return self.frame.origin.y;
}

- (void)setFrameY:(CGFloat)newY {
    self.frame = CGRectMake(self.frame.origin.x, newY,
                            self.frame.size.width, self.frame.size.height);
}

- (CGFloat)frameRight {
    return self.frame.origin.x + self.frame.size.width;
}

- (void)setFrameRight:(CGFloat)newRight {
    self.frame = CGRectMake(newRight - self.frame.size.width, self.frame.origin.y,
                            self.frame.size.width, self.frame.size.height);
}

- (CGFloat)frameBottom {
    return self.frame.origin.y + self.frame.size.height;
}

- (void)setFrameBottom:(CGFloat)newBottom {
    self.frame = CGRectMake(self.frame.origin.x, newBottom - self.frame.size.height,
                            self.frame.size.width, self.frame.size.height);
}

- (CGFloat)frameWidth {
    return self.frame.size.width;
}

- (void)setFrameWidth:(CGFloat)newWidth {
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y,
                            newWidth, self.frame.size.height);
}

- (CGFloat)frameHeight {
    return self.frame.size.height;
}

- (void)setFrameHeight:(CGFloat)newHeight {
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y,
                            self.frame.size.width, newHeight);
}

-(void)roundCorner
{
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = 3.0;
    self.layer.borderWidth = 1.0;
}

-(void)rotateViewStart;
{
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 * 2 ];
    rotationAnimation.duration = 2;
    //rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 0;
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    [self.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}
-(void)rotateViewStop
{
    //CFTimeInterval pausedTime=[self.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    //    self.layer.speed=0.0;
    //    self.layer.timeOffset=pausedTime;
    //self.layer.timeOffset = 0.0;
    //self.layer.beginTime = 0.0;
    //    CFTimeInterval timeSincePause =4+ (pausedTime - (int)pausedTime);
    //    NSLog(@".....%f",timeSincePause);
    //    self.layer.timeOffset=timeSincePause;
    //    self.layer.beginTime = 0.0;
    //    [NSTimer timerWithTimeInterval:timeSincePause target:self selector:@selector(removeAnimation:) userInfo:nil repeats:NO];
    [self.layer removeAllAnimations];
}
- (void)removeAnimation:(id)obj
{
    [self.layer removeAllAnimations];
}
-(void)addSubviews:(UIView *)view,...
{
    [self addSubview:view];
    va_list ap;
    va_start(ap, view);
    UIView *akey=va_arg(ap,id);
    while (akey) {
        [self addSubview:akey];
        akey=va_arg(ap,id);
    }
    va_end(ap);
}

-(void)imageWithURL:(NSString *)url size:(CGSize)size def:(NSString*)def
{
    if (self.frameWidth<kScreenWidth) {
        //大图不展示默认图(首页)
        //地图页需要实际尺寸图
        if([self isKindOfClass:[UIImageView class]]){
            if(!((UIImageView*)self).image)((UIImageView*)self).image = [UIImage imageNamed:def.length?def:@"noImage.png"];
        }else if([self isKindOfClass:[UIButton class]]){
            if(![((UIButton *)self) currentBackgroundImage])[((UIButton *)self) setBackgroundImage:[UIImage imageNamed:def.length?def:@"noImage.png"] forState:UIControlStateNormal];
        }
    }
    //大图片重复请求bug。
    url = [url stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (!url.length) {
        return;
    }
    if ([url rangeOfString:@"http"].length!=4) {
        url = [NSString stringWithFormat:@"%@%@",imageDomain,url];
    }

    NSString *md5Str = url.lastPathComponent.md5?:@"default";
    if ([[Utility defaultsForKey:@"urls"] containsObject:md5Str]) {
        //重复请求bug。下载到一半退出程序？
        return;
    }
    __block NSData *data = [[SDDataCache sharedDataCache] dataFromKey:md5Str fromDisk:YES];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        if (!data.length) {
            [Utility saveToArrayDefaults:md5Str forKey:@"urls"];
            data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
            if (data.length){
                [[SDDataCache sharedDataCache] storeData:data forKey:md5Str toDisk:YES];
            }
            [Utility removeForArrayObj:md5Str forKey:@"urls"];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
            if (data.length) {
                UIImage *image = [UIImage imageWithData:data];
                if (!CGSizeEqualToSize(size, CGSizeZero)) {
                    //image = [image resizeImageWithNewSize:size];
                    CGRect frame = self.frame;
                    if (size.width<0.00001) {
                        frame.size.height = size.height;
                        frame.size.width = image.size.width*frame.size.height/image.size.height;
                    }else if(size.height<0.00001){
                        frame.size.width = size.width;
                        frame.size.height = image.size.height*frame.size.width/image.size.width;
                    }else{
                        frame.size.width = size.width;
                        frame.size.height = size.height;
                    }
                    [self setFrame:frame];
                }
                if([self isKindOfClass:[UIImageView class]]){
                    ((UIImageView*)self).image = image;
                    if([self.superview isKindOfClass:NSClassFromString(@"MyScrollView")]){
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
                        [self.superview performSelector:@selector(resizeImageView)];
#pragma clang diagnostic pop
                    }
                }else if([self isKindOfClass:[UIButton class]]){
                    [((UIButton *)self) setBackgroundImage:image forState:UIControlStateNormal];
                }else{
                    return;
                }
            }
        });
    });
}
-(void)imageWithURL:(NSString *)url
{
    [self imageWithURL:url size:CGSizeZero def:nil];
}
@end
